package com.lx.uitl;

import org.apache.commons.dbcp.BasicDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @title: ConnUtil
 * @projectName jdbc-study
 * @description: 数据库连接工具类
 * @author: yuanChu
 * @date: 2022/4/30  13:09
 */
public class ConnUtil {
    private static ThreadLocal<Connection> threadLocal = new ThreadLocal<>();
    private static DataSource dataSource;

    static {
        Properties properties = new Properties();
        InputStream is = ConnUtil.class.getResourceAsStream("/mysql.properties");
        try {
            properties.load(is);
            dataSource = BasicDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 从本地线程对象ThreadLocal中获取一个连接对象Connection，可能存在的问题是从本地线程池获取的连接对象是没有进行过初始化的，所以要先进行判断该连接标识符指向的内存是否是空，或者是已经关闭了，如果关闭了，则需要从数据源获取新的Connection连接对象
     *
     * @return 连接对象
     * @throws SQLException 在业务层需要处理掉该异常
     */
    public static Connection getConnection() throws SQLException {
        Connection connection = threadLocal.get();
        if (connection == null || connection.isClosed()) {
            connection = dataSource.getConnection();
            threadLocal.set(connection);
        }
        return connection;
    }

    /**
     * 关闭Connection对象
     */
    public static void closeConnection() {
        Connection connection = threadLocal.get();
        try {
            if (connection != null || !connection.isClosed()) {
                connection.close();
            } else {
                threadLocal.set(null);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            threadLocal.set(null);
        }
    }
}
